package com.dubbo.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dubbo.server.mapper.*;
import com.dubbo.server.pojo.*;
import com.dubbo.server.service.map.BackstageUserMapp;
import com.dubbo.server.service.map.UserLikeApi;
import com.dubbo.server.vo.PageVo;
import com.dubbo.server.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper, User> {

    @Reference
    private UserLikeApi userLikeApi;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private PublishInfoMapper publishInfoMapper;


    @Autowired
    private BackstageUserMapp BackstageUserMapp;


    @Autowired
    private FreezeUserMapper userFreezeMapper;


    /**
     * 根据条件查所有用户
     *
     * @return
     */
    public Long getCount() {
        Integer integer = userInfoMapper.selectCount(null);
        return Long.valueOf(integer);
    }


    /**
     * 根据条件获取用户分页数据
     *
     * @param page     当前页码
     * @param pageSize 页尺寸
     * @param id       用户id
     * @param nickname 昵称
     * @param city     居住城市
     * @return 用户分页数据
     */
    public List<PageVo> queryByPage(Integer page, Integer pageSize, Long id, String nickname, String city) {
        //根据id查询
        if (id != null) {
            List<PageVo> listVo = new ArrayList<>();
            PageVo pageVo = new PageVo();
            UserInfo record = userInfoMapper.selectById(id);
            turnPageQuery(listVo, pageVo, record);
            return listVo;
        }
        //根据名称查询
        if (nickname != null & nickname != "") {
            List<PageVo> listVo = new ArrayList<>();
            PageVo pageVo = new PageVo();
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("nick_name", nickname);
            UserInfo record = userInfoMapper.selectOne(queryWrapper);
            turnPageQuery(listVo, pageVo, record);
            return listVo;
        }
//        //根据城市查询（假数据不对）
//        if (city != null & city != "") {
//            List<PageVo> listVo = new ArrayList<>();
//            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
//            queryWrapper.like("city", city);
//            List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
//            for (UserInfo userInfo : userInfos) {
//                PageVo pageVo = new PageVo();
//                turnPageQuery(listVo, pageVo, userInfo);
//            }
//
//            return listVo;
//        }

        //分页查询
        List<PageVo> listVo = new ArrayList<>();
        Page<UserInfo> userPage = new Page<>(page, pageSize);
        Wrapper<UserInfo> wapper = new QueryWrapper<>();
        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(userPage, wapper);
        List<UserInfo> records = userInfoIPage.getRecords();
        for (UserInfo record : records) {
            PageVo pageVo = new PageVo();
            turnPageQuery(listVo, pageVo, record);
        }
        return listVo;
    }

    private void turnPageQuery(List<PageVo> listVo, PageVo pageVo, UserInfo record) {
        pageVo.setId(record.getId());
        if (record.getLogo() != null) {
            pageVo.setLogo(record.getLogo());
            pageVo.setLogoStatus("1");
        } else {
            pageVo.setLogo(null);
            pageVo.setLogoStatus("2");
        }
        pageVo.setNickname(record.getNickName());
        User user = userMapper.selectById(record.getId());
        pageVo.setMobile(user.getMobile());//假的
        pageVo.setSex(String.valueOf(record.getSex()));
        pageVo.setAge(record.getAge());
        pageVo.setIndustry(record.getIndustry());
        //        用户状态，1为正常，2为冻结
        QueryWrapper<UserFreeze> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", record.getId());
        UserFreeze userFreeze = userFreezeMapper.selectOne(wrapper);
        if (userFreeze == null) {
            pageVo.setUserStatus("1");
        } else {
            pageVo.setUserStatus("2");
        }
        Log log = logMapper.selectById(record.getId());
        pageVo.setLastActiveTime(log.getUpdated());//未测试不到能不能用
        pageVo.setCity(record.getCity());
        listVo.add(pageVo);
    }


    /**
     * 根据条件查询用户信息
     *
     * @param userID
     * @return
     */
    public UserVo queryByUid(String userID) {
        UserInfo userInfo = userInfoMapper.selectById(userID);
        User user = userMapper.selectById(userInfo.getId());
        PublishInfo publishInfo = publishInfoMapper.selectById(userInfo.getId());
        Log log = logMapper.selectById(userInfo.getId());
        QueryWrapper<UserFreeze> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userInfo.getId());
        UserFreeze userFreeze = userFreezeMapper.selectOne(wrapper);
//      用户信息
        UserVo userVo = new UserVo();
        userVo.setId(userInfo.getId());//用户ID
        userVo.setNickname(userInfo.getNickName());//昵称
        userVo.setMobile(user.getMobile());//手机号，即用户账号
        userVo.setSex(String.valueOf(userInfo.getSex()));//性别
        //        个性签名
        userVo.setPersonalSignature("人生如戏，且行且珍惜");
        userVo.setAge(userInfo.getAge());//年龄
//        远程有问题
        userVo.setCountBeLiked(userLikeApi.queryFanCount(userInfo.getId()));//被喜欢人数
        userVo.setCountLiked(userLikeApi.queryLikeCount(userInfo.getId()));//喜欢人数
        userVo.setCountMatching(userLikeApi.queryMutualLikeCount(userInfo.getId()));//配对人数
//        userVo.setCountBeLiked(Long.valueOf(publishInfo.getLoveCount()));//被喜欢人数
//        userVo.setCountLiked(Long.valueOf(publishInfo.getLikeCount()));//喜欢人数
//        userVo.setCountMatching(Long.valueOf(publishInfo.getCommentCount()));//配对人数
        userVo.setIncome(userInfo.getIncome());//收入
        userVo.setOccupation(userInfo.getIndustry());//职业,暂无该字段
//        用户状态，1为正常，2为冻结
        if (userFreeze == null) {
            userVo.setUserStatus("1");
        } else {
            userVo.setUserStatus("2");
        }
        userVo.setCreated(publishInfo.getCreated());//注册时间
        userVo.setCity(userInfo.getCity());//注册城市
        userVo.setLastActiveTime(log.getUpdated());//最近活跃时间
        userVo.setLastLoginLocation(log.getPlace());//最近登录地
        userVo.setLogo(userInfo.getLogo());//头像
        userVo.setTags("游戏");//用户标签

        return userVo;
    }


    // 用户冻结
    public Boolean userFreeze(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        try {
            // 冻结操作
            Boolean aBoolean = BackstageUserMapp.userFreeze(userId, freezingTime, freezingRange, reasonsForFreezing, frozenRemarks);
            if (aBoolean) {
                return true;
            }
        } catch (Exception e) {
            log.error("冻结用户失败，userId=" + userId, e);
        }
        return false;
    }

    // 用户手动解冻
    public Boolean userUnfreeze(Long userId, String reasonsForThawing) {
        try {
            Boolean aBoolean = BackstageUserMapp.userUnfreeze(userId, reasonsForThawing);
            if (aBoolean) {
                return true;
            }
        } catch (Exception e) {
            log.error("解冻失败！userId=" + userId, e);
        }
        return false;
    }


}
